require 'widgets/highlightable'
require 'widgets/disableable'
require 'widgets/menu'

module Widgets
  def self.create(name, options)
    if type = options.delete(:type)
      klass = "Widgets::#{type.to_s.classify}".constantize  
      klass.new(name, options)
    else
    end
  end
end

module WidgetsController  
  def self.included(base)
    base.class_eval do 
      extend ClassMethods
      before_filter :init_widgets    
      class_inheritable_accessor :widget_options
      self.widget_options = {}            
    end
  end
  
  module ClassMethods    
    def widget(name, options = {})    
      self.widget_options[name] = options
    end
  end
  
  def init_widgets
    @widgets = {}
    self.class.widget_options.each do |name, options|
      options[:controller] = self
      @widgets[name] = Widgets.create(name, options)
    end
  end  
end

ActionController::Base.class_eval do
  def self.acts_as_widgets_controller
    include WidgetsController unless included_modules.include?(WidgetsController)
  end
end

ActionView::Base.class_eval do
  alias_method :render_without_widget, :render unless method_defined? :render_without_widget
  def render(options = {}, old_local_assigns = {}, &block) #:nodoc:
    if options.is_a?(Hash) and options[:widget].is_a?(Symbol)
      widget = @widgets[options.delete(:widget)]
      # let's be lazy and only build right before we render
      widget.build!
      render :partial => widget.partial, :locals => (options[:locals] || {}).merge(:widget => widget), &block
    else
      render_without_widget(options, old_local_assigns, &block)
    end
  end
end




  
